<?php

namespace App\HttpController\Api;

use App\HttpController\BaseController;
use App\Model\AppFriendsModel;
use App\Model\AppPlatformModel;
use App\Model\MessageModel;
use App\Model\GroupMessageModel;
use App\Model\GroupMessageReadModel;
use App\Model\UserModel;
use App\Model\AppMemberModel;
use App\Model\AppSellerModel;
use App\Model\ApplicationModel;
use App\Model\GroupModel;
use App\Model\GroupUserModel;
use App\Resources\RedisResources;
use EasySwoole\Mysqli\QueryBuilder;
use EasySwoole\ORM\DbManager;


class Message extends BaseController {
    public $imgDomain = 'http://cdn.zczmer.com';
    /**
     * @description
     * @author Mr wang  2019/11/16 下午4:08
     */
    public function chatList() {
        $redisLink = (new RedisResources())->link();
        $userId = $this->request()->getRequestParam('uid');
        $pid = $this->request()->getRequestParam('pid');
        $page = $this->request()->getRequestParam('page');
        if (empty($page)) {
            $page = 1;
        }
        $start = ($page - 1) * 10;
        $chatList = $redisLink->get('clist_' . $userId) ?? '[]';
        print_r($chatList);
        if ($chatList == '[]') {
            $this->setEmptyRedis($userId);
        }
        $chatList = $redisLink->get('clist_' . $userId) ?? '[]';
        if ($chatList) {
            $chatList = json_decode($chatList, true);
            foreach ($chatList as $key => $vv) {
                unset($chatList[$key]['payload']);
            }
        }
        if (!empty($pid)) {
            $appPlatform = AppPlatformModel::create()->where(['id' => $pid])->findOne();
        }

        $queryBuild = new QueryBuilder();
        $sql = "SELECT * FROM `ty_config` where name='text_filtering'";
        $queryBuild->raw($sql);
        $config = DbManager::getInstance()->query($queryBuild, true)->getResult();
        $text_filtering = explode('|', $config[0]['value']);

        foreach ($chatList as $k => $v) {
            $user = UserModel::create()->where(['id' => $v['send_id']])->findOne();
            // $chatList[$k]['store_id'] = $user['store_id'];

            $content = $v['content'];
            foreach ($text_filtering as $val) {
                $content = str_replace($val, '**', $content);
            }
            $chatList[$k]['content'] = $content;
            if ($k == 'id_58295') {
                unset($chatList[$k]);
            }
        }
        $chatList = array_slice($chatList, $start, 10);
        $this->writeJson(200, '消息列表', $chatList);
    }
    public function groupChatList() {
        $redisLink = (new RedisResources())->link();
        $userId = $this->request()->getRequestParam('uid');
        $pid = $this->request()->getRequestParam('pid');
        $page = $this->request()->getRequestParam('page');
        if (empty($page)) {
            $page = 1;
        }
        $start = ($page - 1) * 10;
        $chatList = $redisLink->get('agroupclist_' . $userId) ?? '[]';
        if ($chatList == '[]') {
            $this->setGroupEmptyRedis($userId);
        }
        $chatList = $redisLink->get('agroupclist_' . $userId) ?? '[]';
        if ($chatList) {
            $chatList = json_decode($chatList, true);
            foreach ($chatList as $key => $vv) {
                unset($chatList[$key]['payload']);
            }
        }
        if (!empty($pid)) {
            $appPlatform = AppPlatformModel::create()->where(['id' => $pid])->findOne();
        }

        $queryBuild = new QueryBuilder();
        $sql = "SELECT * FROM `ty_config` where name='text_filtering'";
        $queryBuild->raw($sql);
        $config = DbManager::getInstance()->query($queryBuild, true)->getResult();
        $text_filtering = explode('|', $config[0]['value']);

        foreach ($chatList as $k => $v) {
            // $user = UserModel::create()->where(['id' => $v['send_id']])->findOne();
            // $chatList[$k]['store_id'] = $user['store_id'];

            $content = $v['content'];
            foreach ($text_filtering as $val) {
                $content = str_replace($val, '**', $content);
            }
            $chatList[$k]['content'] = $content;
        }
        $chatList = array_slice($chatList, $start, 10);
        $this->writeJson(200, '群里消息列表', $chatList);
    }

    public function serviceMessage() {
        $userId = $this->request()->getRequestParam('uid');
        $queryBuild = new QueryBuilder();
        // 58295 官方客服
        $sql = "SELECT * FROM (SELECT * FROM ty_messages WHERE ((from_id = {$userId} and send_id = 58295) or (from_id=58295 and send_id = {$userId})) ORDER BY id desc LIMIT 1) r GROUP BY r.from_id ORDER BY r.id desc";
        $queryBuild->raw($sql);
        $chatList = DbManager::getInstance()->query($queryBuild, true)->getResult();
        $data = empty($chatList) ? ['is_read' => 1] : $chatList[0];
        $data['time'] = empty($chatList) ? '' : date('Y-m-d', $data['send_time']);
        $data['id'] = 'id_58295';
        $data['chat_name'] = '技术客服';
        if ($userId == 58295) {
            $data['is_read'] = '1';
        }
        $this->writeJson(200, '消息列表', $data);
    }

    /**
     * 当redis为空时，增加数据
     * @param $userId
     */
    public function setEmptyRedis($userId) {
        //查询好友id
        $member = AppMemberModel::create()->where(['user_id' => $userId])->findOne();
        $friend = AppFriendsModel::create()->where(['member_id' => $member['id']])->select();
        $friend_ids = implode(',', array_column($friend, 'friend_id'));

        $friend_user = UserModel::create()->where("user_id in {$friend_ids}")->select();
        if (empty($friend_user)) {
            $friend_user_ids = '';
            $sql = "SELECT * FROM (SELECT * FROM ty_messages WHERE (from_id = {$userId} or send_id = {$userId}) ORDER BY id desc LIMIT 999999999) r GROUP BY r.from_id ORDER BY r.id desc";
        } else {
            $friend_user_ids = implode(',', array_column($friend_user, 'id'));
            $sql = "SELECT * FROM (SELECT * FROM ty_messages WHERE ((from_id = {$userId} and send_id in ({$friend_user_ids})) or (send_id = {$userId} and from_id in ({$friend_user_ids}))) ORDER BY id desc LIMIT 999999999) r GROUP BY r.from_id ORDER BY r.id desc";
        }

        $queryBuild = new QueryBuilder();
        print_r($sql);
        $queryBuild->raw($sql);
        $chatList = DbManager::getInstance()->query($queryBuild, true)->getResult();

        foreach ($chatList as $v) {
            $this->sendChatListUpdate($v);
        }
    }

    /**
     * 当redis为空时，增加数据
     * @param $userId
     */
    public function setGroupEmptyRedis($userId) {

        $queryBuild = new QueryBuilder();
        $groups = GroupUserModel::create()->where(['user_id' => $userId])->select();
        if ($groups) {
            $group_ids = implode(',', array_column($groups, 'group_id'));
            $sql = "SELECT * FROM (SELECT * FROM ty_group_message WHERE group_id in ({$group_ids}) ORDER BY id desc LIMIT 999999999) r GROUP BY r.group_id ORDER BY r.id asc";
            $queryBuild->raw($sql);
            $chatList = DbManager::getInstance()->query($queryBuild, true)->getResult();

            foreach ($chatList as $v) {
                $this->sendGroupChatListUpdate($v, $userId);
            }
        }
    }

    public function getUnreadTotal() {
        $userId = $this->request()->getRequestParam('uid');
        $where = [
            'send_id' => $userId,
            'is_read' => 0
        ];
        $msg_total = MessageModel::create()->where($where)->select();
        $group_total = GroupMessageReadModel::create()->where(['user_id' => $userId, 'is_read' => 0])->select();
        $this->writeJson(200, '未读消息总数', ['msg_total' => count($msg_total), 'group_total' => count($group_total)]);
    }

    public function getCommentTotal() {
        $userId = $this->request()->getRequestParam('uid');
        $where = [
            'send_id' => $userId,
            'is_read' => 0
        ];
        $total = MessageModel::create()->where($where)->select();

        $this->writeJson(200, '未读消息总数', count($total));
    }
    public function getapplicationTotal() {
        $userId = $this->request()->getRequestParam('user_id');
        $where = [
            'sid' => $userId,
            'status' => 1
        ];
        $total = ApplicationModel::create()->where($where)->select();

        $this->writeJson(200, '申请数量', count($total));
    }

    /**
     * 聊天记录列表
     * @description
     * @throws \EasySwoole\ORM\Exception\Exception
     * @throws \Throwable
     * @author Mr wang  2019/11/16 下午3:41
     */
    public function messageList() {
        $params = $this->request()->getRequestParam();
        $page_no = $params['page_no'];
        $from = UserModel::create()->where("id={$params['from_id']}")->findOne();
        $send = UserModel::create()->where("id={$params['send_id']}")->findOne();

        $friend = AppFriendsModel::create()->where("(member_id={$send['user_id']} and friend_id={$from['user_id']}) or (member_id={$from['user_id']} and friend_id={$send['user_id']})")->findOne();
        // var_dump($friend);
        $add_friend_time=0;
        if($friend){
            $add_friend_time = $friend['add_time'];
        }

        $page = ($page_no - 1) * 20;
        $where = "((send_id={$params['send_id']} and from_id = {$params['from_id']}) or (send_id={$params['from_id']} and from_id = {$params['send_id']})) and send_time > {$add_friend_time}";
        $messageList = MessageModel::create()->where($where)->limit($page, 20)->order('id', 'desc')->select();

        $queryBuild = new QueryBuilder();
        $sql = "SELECT * FROM `ty_config` where name='text_filtering'";
        $queryBuild->raw($sql);
        $config = DbManager::getInstance()->query($queryBuild, true)->getResult();
        $text_filtering = explode('|', $config[0]['value']);

        foreach ($messageList as &$val) {
            if ($val['msg_type'] == 2 || $val['msg_type'] == 4 || $val['msg_type'] == 5) {
                $val['content'] =  $this->imgDomain . $val['content'];
            } else if ($val['msg_type'] == 7 || $val['msg_type'] == 8) {
                $val['content'] = htmlspecialchars_decode(\str_ireplace('src=&quot;/', 'src="https://cdn.zczmer.com/', $val['content']));
            } else if ($val['msg_type'] == 1) {
                foreach ($text_filtering as $v) {
                    $val['content'] = str_replace($v, '**', $val['content']);
                }
            } else {
                $val['content'];
            }
            // $val['content'] = ($val['msg_type'] == 2 || $val['msg_type'] == 4 || $val['msg_type'] == 5) ? $this->imgDomain . $val['content'] : $val['content'];
            $val['video_img'] = $this->imgDomain . $val['video_img'];
            $val['from'] = $from;
            $val['send'] = $send;
            if ($val['quote']) {
                $val['quote'] = json_decode($val['quote'], true);
            }
            $val['content'] = htmlspecialchars_decode($val['content']);
            //$val['send_time'] = strtotime($val['send_time']);
        }
        $data['send_id'] = $params['from_id'];
        $data['from_id'] = $params['send_id'];
        $data['msg_type'] = 'msg';
        $this->msgRead($data);
        $this->writeJson(200, '消息详情列表', $messageList);
    }
    /**
     * 群聊天记录列表
     * @description
     * @throws \EasySwoole\ORM\Exception\Exception
     * @throws \Throwable
     * @author Mr wang  2019/11/16 下午3:41
     */
    public function groupMessageList() {
        $params = $this->request()->getRequestParam();
        $page_no = $params['page_no'];

        $page = ($page_no - 1) * 20;
        $where = ['group_id' => $params['send_id']];
        $messageList = GroupMessageModel::create()->where($where)->limit($page, 20)->order('id', 'desc')->select();

        $queryBuild = new QueryBuilder();
        $sql = "SELECT * FROM `ty_config` where name='text_filtering'";
        $queryBuild->raw($sql);
        $config = DbManager::getInstance()->query($queryBuild, true)->getResult();
        $text_filtering = explode('|', $config[0]['value']);

        foreach ($messageList as &$val) {
            $from = UserModel::create()->where("id={$val['user_id']}")->findOne();
            $fromGroupUserInfo = GroupUserModel::create()->where("user_id={$val['user_id']} and group_id={$val['group_id']}")->findOne();
            $from['name'] = $fromGroupUserInfo['nickname'] ? $fromGroupUserInfo['nickname'] : $from['name'];
            // $send = UserModel::create()->where("id={$params['send_id']}")->findOne();
            if ($val['msg_type'] == 2 || $val['msg_type'] == 4 || $val['msg_type'] == 5) {
                $val['content'] =  $this->imgDomain . $val['content'];
            } else if ($val['msg_type'] == 7) {
                $val['content'] = htmlspecialchars_decode(\str_ireplace('src=&quot;/', 'src="https://cdn.zczmer.com/', $val['content']));
            } else if ($val['msg_type'] == 1) {
                foreach ($text_filtering as $v) {
                    $val['content'] = str_replace($v, '**', $val['content']);
                }
            } else {
                $val['content'];
            }
            // $val['content'] = ($val['msg_type'] == 2 || $val['msg_type'] == 4 || $val['msg_type'] == 5) ? $this->imgDomain . $val['content'] : $val['content'];
            $val['video_img'] = $this->imgDomain . $val['video_img'];
            $val['from'] = $from;
            // $val['send'] = $send;
            //$val['send_time'] = strtotime($val['send_time']);
            $val['from_id'] = $val['user_id'];
            if ($val['quote']) {
                $val['quote'] = json_decode($val['quote'], true);
            }
            $val['content'] = htmlspecialchars_decode($val['content']);
        }
        // $data['send_id'] = $params['send_id'];
        // $data['user_id'] = $params['send_id'];
        // $data['msg_type'] = 'msg';
        // $this->msgRead($data);
        $this->writeJson(200, '消息详情列表', $messageList);
    }
    /**
     * 聊天记录列表
     * @description
     * @throws \EasySwoole\ORM\Exception\Exception
     * @throws \Throwable
     * @author Mr wang  2019/11/16 下午3:41
     */
    public function searchMessage() {
        $params = $this->request()->getRequestParam();
        $page_no = $params['page_no'];

        $page = ($page_no - 1) * 20;
        $where = "(send_id={$params['user_id']} or from_id = {$params['user_id']})";
        if ($params['keywords']) {
            $where .= " and content like %{$params['keywords']}%";
        }
        $messageList = MessageModel::create()->where($where)->limit($page, 20)->order('id', 'desc')->select();
        foreach ($messageList as &$val) {
            $from = UserModel::create()->where("id={$params['from_id']}")->findOne();
            $send = UserModel::create()->where("id={$params['send_id']}")->findOne();
            $val['content'] = ($val['msg_type'] == 2 || $val['msg_type'] == 4 || $val['msg_type'] == 5) ? $this->imgDomain . $val['content'] : $val['content'];
            $val['video_img'] = $this->imgDomain . $val['video_img'];
            $val['from'] = $from;
            $val['send'] = $send;
            //$val['send_time'] = strtotime($val['send_time']);
        }
        $this->writeJson(200, '搜索聊天记录列表', $messageList);
    }


    /**
     * 获取发送者接受者信息
     */
    public function getSendFromInfo() {
        $params = $this->request()->getRequestParam();
    }

    /**
     * 初始化消息类型
     * @description
     * @author Mr wang  2019/11/17 0:15
     * @param $server
     * @param $fd
     * @param $data
     * @throws \EasySwoole\ORM\Exception\Exception
     * @throws \EasySwoole\Redis\Exception\RedisException
     * @throws \Throwable
     */
    public function initMessage($server, $fd, $data) {
        print_r('消息：' . $data . PHP_EOL);
        $data = json_decode($data, true);
        if (isset($data['event'])) {
            $server->push($fd, json_encode(['event' => 'pong']));
        } else {
            if ($data['type'] == 'record') {
                // 如果是发送录音信息
                print_r('录音调试' . PHP_EOL);
                print_r($data);
                $this->sendRecordClient($server, $data);
                return;
                //$server->push($fd, json_encode($data));
            } else if ($data['type'] == 'friend') {
                if ($data['msg_type'] == 'Application') { //申请
                    //获取被申请人
                    $send = UserModel::create()->where("id={$data['send_id']}")->findOne();
                    $member = AppMemberModel::create()->where(['id' => $send['user_id']])->findOne();
                    $send_id = $data['send_id'];
                    $redisLink = (new RedisResources())->link();
                    $app_send_fd = $redisLink->get('app_user_' . $send_id);
                    $h5_send_fd = $redisLink->get('h5_user_' . $send_id);
                    $where = [
                        'sid' => $member['id'],
                        'status' => 1
                    ];
                    $total = ApplicationModel::create()->where($where)->select();
                    $data['count'] = count($total);
                    if ($app_send_fd) {
                        $server->push($app_send_fd, json_encode($data));
                    }
                    if ($h5_send_fd) {
                        $server->push($h5_send_fd, json_encode($data));
                    }
                } else if ($data['msg_type'] == 'adopt') {
                }
            } elseif ($data['type'] == 'comment') {
                $from_id = $data['from_id'];
                $redisLink = (new RedisResources())->link();
                $app_from_fd = $redisLink->get('app_user_' . $from_id);
                $h5_from_fd = $redisLink->get('h5_user_' . $from_id);

                // print_r($from_fd);
                print_r('返回' . json_encode($data) . '评论数据给：' . $data['from_id'] . $app_from_fd . PHP_EOL);
                print_r('返回' . json_encode($data) . '评论数据给：' . $data['from_id'] . $h5_from_fd . PHP_EOL);
                // print_r($data);
                $server->push($app_from_fd, json_encode($data));
                $server->push($h5_from_fd, json_encode($data));
                $send_ids = $data['send_id'];
                foreach ($send_ids as $send_id) {
                    $app_send_fd = $redisLink->get('app_user_' . $send_id);
                    $h5_send_fd = $redisLink->get('h5_user_' . $send_id);

                    if ($app_send_fd) {
                        print_r('发送' . json_encode($data) . '评论数据给：' . $send_id . $app_send_fd . PHP_EOL);
                        $server->push($app_send_fd, json_encode($data));
                    }
                    if ($h5_send_fd) {
                        print_r('发送' . json_encode($data) . '评论数据给：' . $send_id . $h5_send_fd . PHP_EOL);
                        $server->push($h5_send_fd, json_encode($data));
                    }
                }
            } elseif ($data['type'] == 'sc') {
                $send_id = $data['send_id'];
                //查询接收者是否在线
                $redisLink = (new RedisResources())->link();
                $app_send_fd = $redisLink->get('app_user_' . $send_id);
                $h5_send_fd = $redisLink->get('h5_user_' . $send_id);
                if ($app_send_fd) {
                    print_r('我要转发消息给' . $send_id . PHP_EOL);
                    $server->push($app_send_fd, json_encode($data));
                }
                if ($h5_send_fd) {
                    print_r('我要转发消息给' . $send_id . PHP_EOL);
                    $server->push($h5_send_fd, json_encode($data));
                }
            } else {
                $data['send_time'] = time();
                $from = UserModel::create()->where("id={$data['from_id']}")->findOne();
                $data['from'] = $from;
                $data['send'] = $from;

                $from_id = $data['from_id'];
                $redisLink = (new RedisResources())->link();
                $app_from_fd = $redisLink->get('app_user_' . $from_id);
                $h5_from_fd = $redisLink->get('h5_user_' . $from_id);
                if (isset($data['msg_type']) && $data['msg_type'] == 2) {
                    $data['img_url'] = $data['content'];
                    $data['content'] = $this->imgDomain . $data['content'];
                }

                if (isset($data['msg_type']) && $data['msg_type'] == 4) {
                    $data['audio_url'] = $data['content'];
                    $data['content'] = $this->imgDomain . $data['content'];
                }

                if (isset($data['msg_type']) && $data['msg_type'] == 5) {
                    $data['video_url'] = $data['content'];
                    $data['video_img_url'] = $data['video_img'];
                    $data['content'] = $this->imgDomain . $data['content'];
                    $data['video_img'] = $this->imgDomain . $data['video_img'];
                }
                $return_data = $data;

                // 文字消息返回数据走过滤和翻译
                if ($data['msg_type'] == 1) {
                    $queryBuild = new QueryBuilder();
                    $sql = "SELECT * FROM `ty_config` where name='text_filtering'";
                    $queryBuild->raw($sql);
                    $config = DbManager::getInstance()->query($queryBuild, true)->getResult();
                    $text_filtering = explode('|', $config[0]['value']);
                    foreach ($text_filtering as $v) {
                        $return_data['content'] = str_replace($v, '**', $return_data['content']);
                    }

                    //私聊消息才走翻译接口
                    if ($data['type'] == MSG) {
                        $queryBuild = new QueryBuilder();
                        $sql = "SELECT a.*,c.title FROM ty_user AS a LEFT JOIN ty_app_member b ON b.id = a.user_id LEFT JOIN ty_language c ON c.lg_id = b.lg_id  WHERE a.id = {$data['send_id']}";
                        $queryBuild->raw($sql);
                        $send_user = DbManager::getInstance()->query($queryBuild, true)->getResult();
                        $sql = "SELECT a.*,c.title FROM ty_user AS a LEFT JOIN ty_app_member b ON b.id = a.user_id LEFT JOIN ty_language c ON c.lg_id = b.lg_id  WHERE a.id = {$data['from_id']}";
                        $queryBuild->raw($sql);
                        $from_user = DbManager::getInstance()->query($queryBuild, true)->getResult();
                        $from = $from_user[0]['title'];
                        $to = $send_user[0]['title'];
                        if ($send_user[0]['platform_id'] == 3 && $from != $to) {

                            $fanyi = $this->fanyi($data['content'], $from, $to);
                            $fanyi = json_decode($fanyi, true);

                            $data['content_fanyi'] = $fanyi['trans_result'][0]['dst'];
                            $data['from_title'] = $from;
                            $data['to_title'] = $to;
                        }
                    }
                }


                // print_r($from_fd);
                print_r('返回' . json_encode($return_data) . '数据给：' . $data['from_id'] . $app_from_fd . PHP_EOL);
                print_r('返回' . json_encode($return_data) . '数据给：' . $data['from_id'] . $h5_from_fd . PHP_EOL);
                print_r($data);
                if ($app_from_fd) {
                    $server->push($app_from_fd, json_encode($return_data));
                }
                if ($h5_from_fd) {
                    $server->push($h5_from_fd, json_encode($return_data));
                }
            }
            switch ($data['type']) {
                case MSG:
                case DEAL:
                    $this->sendClient($server, $data);
                    break;
                case GROUP:
                    $this->sendGroupClient($server, $data);
                    break;
                case READ_BACK:
                    $this->msgRead($data);
                    break;
            }
        }
        // echo json_encode($data);
    }


    /**
     * 群聊消息发送
     * @description
     * @author Mr wang  2019/11/17 0:15
     * @param $server
     * @param $data
     * @throws \EasySwoole\ORM\Exception\Exception
     * @throws \EasySwoole\Redis\Exception\RedisException
     * @throws \Throwable
     */
    public function sendGroupClient($server, $data) {
        $send_id = $data['send_id'];

        print_r('走到群聊发消息' . PHP_EOL);
        //同步mysql储存消息
        $this->saveMessage($data);
        //保存完过滤屏蔽词
        $queryBuild = new QueryBuilder();
        $sql = "SELECT * FROM `ty_config` where name='text_filtering'";
        $queryBuild->raw($sql);
        $config = DbManager::getInstance()->query($queryBuild, true)->getResult();
        $text_filtering = explode('|', $config[0]['value']);
        foreach ($text_filtering as $v) {
            $data['content'] = str_replace($v, '**', $data['content']);
        }
        $from_user = GroupUserModel::create()->where(["group_id" => $data['send_id'], 'user_id' => $data['from_id']])->findOne();
        $data['from']['name'] = $from_user['nickname'] ? $from_user['nickname'] : $from_user['user_name'];
        //生成会话列表 同时给 发送者 和 接收者生成/更新 会话
        $this->groupChatListUpdate($data);



        $group_member = GroupUserModel::create()->where(["group_id" => $data['send_id']])->select();
        $quote = isset($data['quote']) ? $data['quote'] : false;
        foreach ($group_member as $v) {
            if (($v['remind_flag'] == 0 || ($quote && $quote['user_id'] == $v['user_id'])) && $v['user_id'] != $data['from_id']) {

                //发送通知
                // print_r('我要发群聊通知给' . $send_id . PHP_EOL.json_encode($data). PHP_EOL);
                $send_data = $data;
                $send_data['send_id'] = $v['user_id'];
                $send_data['group_id'] = $data['send_id'];
                $this->sendGroupNotice($send_data);
            }
            if ($data['from_id'] != $v['user_id']) {
                //查询接收者是否在线
                $redisLink = (new RedisResources())->link();
                $app_send_fd = $redisLink->get('app_user_' . $v['user_id']);
                $h5_send_fd = $redisLink->get('h5_user_' . $v['user_id']);
                if ($app_send_fd) {
                    print_r('我要转发消息给' . $send_id . PHP_EOL);
                    $server->push($app_send_fd, json_encode($data));
                }
                if ($h5_send_fd) {
                    print_r('我要转发消息给' . $send_id . PHP_EOL);
                    $server->push($h5_send_fd, json_encode($data));
                }
            }
        }
    }
    /**
     * 发送通知
     * @param $data
     * @return void
     */
    public function sendGroupNotice($data) {
        //处理通知
        $info = [];
        $from = UserModel::create()->where("id = " . $data['from_id'])->findOne();
        $send = UserModel::create()->where("id = " . $data['send_id'])->findOne();
        $group = GroupModel::create()->where("id = " . $data['group_id'])->findOne();


        $info['send']  = ['open_id' => $send['open_id'], 'cid' => $send['cid']];
        $info['from']  = ['nick_name' => $from['name'], 'group_name' => $group['group_name']];
        if ($data['msg_type'] == 2) {
            $data['content'] = '[图片]';
        } elseif ($data['msg_type'] == 4) {
            $data['content'] = '[语音]';
        } elseif ($data['msg_type'] == 5) {
            $data['content'] = '[视频]';
        } else {
            $data['content'] = $data['content'];
        }

        if ($info['send']['cid']) {
            $app_param['cids'] = $info['send']['cid'];
            $app_param['title'] = '群聊：' . $info['from']['group_name'];
            $app_param['content'] = $info['from']['nick_name'] . '：' . $data['content'];
            $app_param['payload'] = $data['payload'];
            $url = 'https://shop.zczmer.com/WXAPI/App/sendPush';
            $res = $this->httpRequest($url, 'POST', json_encode($app_param));
            print_r('推送通知返回数据' . json_encode($res) . PHP_EOL);
        }
    }
    /**
     * 更新群聊消息列表
     * @description
     * @param $data
     * @throws \EasySwoole\Redis\Exception\RedisException
     * @author Mr wang  2019/11/16 下午4:01
     */
    public function groupChatListUpdate($data) {
        $redisLink = (new RedisResources())->link();

        // $from_id = $data['from_id']; //927
        $group_id = $data['send_id']; //925
        $group_member = GroupUserModel::create()->where(["group_id" => $group_id])->select();
        $group = GroupModel::create()->where(["id" => $group_id])->findOne();
        $from_user = GroupUserModel::create()->where(["group_id" => $group_id, 'user_id' => $data['from_id']])->findOne();

        //更新接收者未读会话
        //获取接收者的会话列表
        foreach ($group_member as $v) {
            $from_id = $v['user_id'];
            $send_list = $redisLink->get('agroupclist_' . $from_id) ?? '[]';
            if ($send_list == '[]') {
                $this->setEmptyRedis($from_id);
                $send_list = $redisLink->get('agroupclist_' . $from_id) ?? '[]';
            }
            $send_list = json_decode($send_list, true);

            unset($send_list['id_' . $group_id]);
            $send_arr['id_' . $group_id] = $data;
            $send_arr['id_' . $group_id]['is_read'] = $data['from_id'] == $v['user_id'] ? 1 : 0;
            $send_arr['id_' . $group_id]['send_name'] = $group['group_name'];
            $send_arr['id_' . $group_id]['from_name'] = $from_user['nickname'] ? $from_user['nickname'] : $from_user['user_name'];
            $send_arr['id_' . $group_id]['time'] = date('Y-m-d');
            $send_arr['id_' . $group_id]['chat_name'] = $group['group_name'];
            $send_arr['id_' . $group_id]['chat_nickname'] = $v['group_nickname'];
            $send_arr['id_' . $group_id]['chat_img'] = array_column($group_member, 'img');
            // $send_list[$from_id] = $data;
            // $send_list[$from_id]['is_read'] = 0; //接收者的对应该发送者发送的信息设置为未读
            $send_list = array_merge($send_arr, $send_list);

            $redisLink->set('agroupclist_' . $from_id, json_encode($send_list)); //clist_1_93

        }
    }

    // 删除redis 群聊记录
    public function delGroupChatList($userId, $groupId) {
        $redisLink = (new RedisResources())->link();
        $send_list = $redisLink->get('agroupclist_' . $userId) ?? '[]';
        $send_list = json_decode($send_list, true);
        unset($send_list['id_' . $groupId]);
        $redisLink->set('agroupclist_' . $userId, json_encode($send_list)); //clist_1_93
    }

    /**
     * 消息发送
     * @description
     * @author Mr wang  2019/11/17 0:15
     * @param $server
     * @param $data
     * @throws \EasySwoole\ORM\Exception\Exception
     * @throws \EasySwoole\Redis\Exception\RedisException
     * @throws \Throwable
     */
    public function sendClient($server, $data) {
        $send_id = $data['send_id'];

        print_r('走到转发了' . PHP_EOL);
        //同步mysql储存消息
        $this->saveMessage($data);

        //保存完过滤屏蔽词
        $queryBuild = new QueryBuilder();
        $sql = "SELECT * FROM `ty_config` where name='text_filtering'";
        $queryBuild->raw($sql);
        $config = DbManager::getInstance()->query($queryBuild, true)->getResult();
        $text_filtering = explode('|', $config[0]['value']);
        foreach ($text_filtering as $v) {
            $data['content'] = str_replace($v, '**', $data['content']);
        }
        //生成会话列表 同时给 发送者 和 接收者生成/更新 会话
        $this->chatListUpdate($data);

        //发送通知
        print_r('我要发通知给' . $send_id . PHP_EOL);
        $this->sendNotice($data);


        //查询接收者是否在线
        $redisLink = (new RedisResources())->link();
        $app_send_fd = $redisLink->get('app_user_' . $send_id);
        $h5_send_fd = $redisLink->get('h5_user_' . $send_id);
        if ($app_send_fd) {
            print_r('我要转发消息给' . $send_id . PHP_EOL);
            $server->push($app_send_fd, json_encode($data));
        }
        if ($h5_send_fd) {
            print_r('我要转发消息给' . $send_id . PHP_EOL);
            $server->push($h5_send_fd, json_encode($data));
        }
    }

    /**
     * 保存消息
     * @description
     * @param $data
     * @throws \EasySwoole\ORM\Exception\Exception
     * @throws \Throwable
     * @author Mr wang  2019/11/16 下午3:54
     */
    public function saveMessage($data) {
        // $queryBuild = new QueryBuilder();
        // $sql = "SELECT a.*,c.title FROM ty_user AS a LEFT JOIN ty_app_member b ON b.id = a.user_id LEFT JOIN ty_language c ON c.lg_id = b.lg_id  WHERE a.id = {$data['send_id']}";
        // $queryBuild->raw($sql);
        // $send_user = DbManager::getInstance()->query($queryBuild, true)->getResult();
        // $sql = "SELECT a.*,c.title FROM ty_user AS a LEFT JOIN ty_app_member b ON b.id = a.user_id LEFT JOIN ty_language c ON c.lg_id = b.lg_id  WHERE a.id = {$data['from_id']}";
        // $queryBuild->raw($sql);
        // $from_user = DbManager::getInstance()->query($queryBuild, true)->getResult();
        // $from = $from_user[0]['title'];
        // $to = $send_user[0]['title'];
        // if($data['msg_type']==1&&$send_user[0]['platform_id']==3&&$from!=$to){

        //     $fanyi = $this->fanyi($data['content'],$from,$to);
        //     $fanyi = json_decode($fanyi,true);

        //     $params['content_fanyi'] = $fanyi['trans_result'][0]['dst'];
        //     $params['from_title'] = $from;
        //     $params['to_title'] = $to;
        // }
        if ($data['type'] == 'msg') {
            $params = [
                'send_id' => $data['send_id'],
                'from_id' => $data['from_id'],
                'content' => $data['msg_type'] == 3 || $data['msg_type'] == 6 || $data['msg_type'] == 7  || $data['msg_type'] == 8 ?
                    json_encode($data['content']) : ($data['msg_type'] == 2 ? $data['img_url'] : ($data['msg_type'] == 4 ? $data['audio_url'] : ($data['msg_type'] == 5 ? $data['video_url'] : $data['content']))),
                'msg_type' => $data['msg_type'],
                'type' => $data['type'],
                'send_time' => $data['send_time'],
                'video_img' => $data['video_img_url'] ?? '',
                'second' => $data['msg_type'] == 4 ? $data['second'] : 0,
                'content_fanyi' => $data['content_fanyi'] ?? null,
                'from_title' => $data['from_title'] ?? null,
                'to_title' => $data['to_title'] ?? null,
            ];
            if (isset($data['quote'])) {
                $params['quote'] = json_encode($data['quote']);
            }
            MessageModel::create($params)->save();
        }
        if($data['type']=='deal'){
            $params = [
                'send_id' => $data['send_id'],
                'from_id' => $data['from_id'],
                'content' => json_encode($data['content']),
                'msg_type' => $data['msg_type'],
                'type' => $data['type'],
                'send_time' => $data['send_time'],
                'video_img' => $data['video_img_url'] ?? '',
                'second' => $data['second'] ?? 0,
                'content_fanyi' => $data['content_fanyi'] ?? null,
                'from_title' => $data['from_title'] ?? null,
                'to_title' => $data['to_title'] ?? null,
            ];
            MessageModel::create($params)->save();
        }
        if ($data['type'] == 'group') {
            $params = [
                'group_id' => $data['send_id'],
                'user_id' => $data['from_id'],
                'content' => $data['msg_type'] == 3 || $data['msg_type'] == 6 || $data['msg_type'] == 7 || $data['msg_type'] == 8 ?
                    json_encode($data['content']) : ($data['msg_type'] == 2 ? $data['img_url'] : ($data['msg_type'] == 4 ? $data['audio_url'] : ($data['msg_type'] == 5 ? $data['video_url'] : $data['content']))),
                'msg_type' => $data['msg_type'],
                'send_time' => $data['send_time'],
                'video_img' => $data['video_img_url'] ?? '',
                'second' => $data['msg_type'] == 4 ? $data['second'] : 0,
            ];
            if (isset($data['quote'])) {
                $params['quote'] = json_encode($data['quote']);
            }
            GroupMessageModel::create($params)->save();
            $group_member = GroupUserModel::create()->where(["group_id" => $data['send_id']])->select();
            foreach ($group_member as $v) {
                $read_data = [
                    'group_id' => $data['send_id'],
                    'from_id' => $data['from_id'],
                    'user_id' => $v['user_id'],
                    'is_read' => $data['from_id'] == $v['user_id'] ? 1 : 0,
                ];
                GroupMessageReadModel::create($read_data)->save();
            }
        }
    }

    /**
     * 更新消息列表
     * @description
     * @param $data
     * @throws \EasySwoole\Redis\Exception\RedisException
     * @author Mr wang  2019/11/16 下午4:01
     */
    public function chatListUpdate($data) {
        $redisLink = (new RedisResources())->link();

        $from_id = $data['from_id']; //927
        $send_id = $data['send_id']; //925
        $from_user = UserModel::create()->where(["id" => $from_id])->findOne();
        $send_user = UserModel::create()->where(["id" => $send_id])->findOne();

        //更新接收者未读会话
        //获取接收者的会话列表
        $send_list = $redisLink->get('clist_' . $send_id) ?? '[]';
        if ($send_list == '[]') {
            $this->setEmptyRedis($send_id);
            $send_list = $redisLink->get('clist_' . $send_id) ?? '[]';
        }
        $send_list = json_decode($send_list, true);

        unset($send_list['id_' . $from_id]);
        $send_arr['id_' . $from_id] = $data;
        $send_arr['id_' . $from_id]['is_read'] = 0;
        $send_arr['id_' . $from_id]['send_name'] = $send_user['name'];
        $send_arr['id_' . $from_id]['from_name'] = $from_user['name'];
        $send_arr['id_' . $from_id]['time'] = date('Y-m-d');
        $send_arr['id_' . $from_id]['chat_name'] = $from_user['name'];
        $send_arr['id_' . $from_id]['chat_img'] = $from_user['img'];
        // $send_list[$from_id] = $data;
        // $send_list[$from_id]['is_read'] = 0; //接收者的对应该发送者发送的信息设置为未读
        $send_list = array_merge($send_arr, $send_list);

        $redisLink->set('clist_' . $send_id, json_encode($send_list)); //clist_1_93

        //给发送者增加会话列表
        $from_list = $redisLink->get('clist_' . $from_id) ?? "[]"; //clist_1_1395获取发送者的会话列表

        if ($from_list == '[]') {
            $this->setEmptyRedis($from_id);
            $from_list = $redisLink->get('clist_' . $from_id) ?? '[]';
        }

        $from_list = json_decode($from_list, true);


        unset($from_list['id_' . $send_id]);
        $from_arr['id_' . $send_id] = $data;
        $from_arr['id_' . $send_id]['is_read'] = 1;
        $from_arr['id_' . $send_id]['send_name'] = $send_user['name'];
        $from_arr['id_' . $send_id]['from_name'] = $from_user['name'];
        $from_arr['id_' . $send_id]['time'] = date('Y-m-d');
        $from_arr['id_' . $send_id]['chat_name'] = $send_user['name'];
        $from_arr['id_' . $send_id]['chat_img'] = $send_user['img'];
        // $from_list[$send_id] = $data;
        // $from_list[$send_id]['is_read'] = 1;
        $from_list = array_merge($from_arr, $from_list);
        $redisLink->set('clist_' . $from_id, json_encode($from_list));
    }

    /**
     * 更新消息列表
     * @description
     * @param $data
     * @throws \EasySwoole\Redis\Exception\RedisException
     * @author Mr wang  2019/11/16 下午4:01
     */
    public function sendChatListUpdate($data) {
        $redisLink = (new RedisResources())->link();

        $from_id = $data['from_id']; //927
        $send_id = $data['send_id']; //925
        $from_user = UserModel::create()->where(["id" => $from_id])->findOne();
        $send_user = UserModel::create()->where(["id" => $send_id])->findOne();

        //更新接收者未读会话
        //获取接收者的会话列表
        $send_list = $redisLink->get('clist_' . $send_id) ?? '[]';

        $send_list = json_decode($send_list, true);

        unset($send_list['id_' . $from_id]);
        $send_arr['id_' . $from_id] = $data;
        $send_arr['id_' . $from_id]['is_read'] = 1;
        $send_arr['id_' . $from_id]['send_name'] = $send_user['name'];
        $send_arr['id_' . $from_id]['from_name'] = $from_user['name'];
        $send_arr['id_' . $from_id]['time'] = date('Y-m-d');
        $send_arr['id_' . $from_id]['chat_name'] = $from_user['name'];
        $send_arr['id_' . $from_id]['chat_img'] = $from_user['img'];
        // $send_list[$from_id] = $data;
        // $send_list[$from_id]['is_read'] = 0; //接收者的对应该发送者发送的信息设置为未读
        $send_list = array_merge($send_arr, $send_list);

        $redisLink->set('clist_' . $send_id, json_encode($send_list)); //clist_1_93
    }
    /**
     * 更新群聊消息列表
     * @description
     * @param $data
     * @throws \EasySwoole\Redis\Exception\RedisException
     * @author Mr wang  2019/11/16 下午4:01
     */
    public function sendGroupChatListUpdate($data, $userId) {
        $redisLink = (new RedisResources())->link();

        $from_id = $data['user_id'];
        $group_id = $data['group_id']; //925
        $group = GroupModel::create()->where(["id" => $group_id])->findOne();
        $group_member = GroupUserModel::create()->where(["group_id" => $group_id])->select();
        $my_group_info = GroupUserModel::create()->where(["group_id" => $group_id, 'user_id' => $userId])->findOne();
        $from_user = GroupUserModel::create()->where(["group_id" => $group_id, 'user_id' => $from_id])->findOne();
        // $send_user = UserModel::create()->where(["id" => $send_id])->findOne();

        //更新接收者未读会话
        //获取接收者的会话列表
        $send_list = $redisLink->get('agroupclist_' . $userId) ?? '[]';

        $send_list = json_decode($send_list, true);

        unset($send_list['id_' . $group_id]);
        $send_arr['id_' . $group_id] = $data;
        $send_arr['id_' . $group_id]['is_read'] = 1;
        $send_arr['id_' . $group_id]['send_name'] = $group['name'];
        $send_arr['id_' . $group_id]['from_name'] = $from_user['nickname'] ? $from_user['nickname'] : $from_user['user_name'];
        $send_arr['id_' . $group_id]['time'] = date('Y-m-d');
        $send_arr['id_' . $group_id]['chat_name'] = $group['group_name'];
        $send_arr['id_' . $group_id]['chat_nickname'] = $my_group_info['group_nickname'];
        $send_arr['id_' . $group_id]['chat_img'] = array_column($group_member, 'img');
        // $send_list[$from_id] = $data;
        // $send_list[$from_id]['is_read'] = 0; //接收者的对应该发送者发送的信息设置为未读
        $send_list = array_merge($send_arr, $send_list);

        $redisLink->set('agroupclist_' . $userId, json_encode($send_list)); //clist_1_93
    }

    /**
     * 将会话列表设置为已读
     * @description
     * @author Mr wang  2019/11/17 0:15
     * @param $data
     * @throws \EasySwoole\Redis\Exception\RedisException
     */
    public function msgRead($data) {
        $redisLink = (new RedisResources())->link();
        $msg_type = $data['msg_type'] ?? 'msg';

        if ($msg_type == 'msg'||$msg_type=='deal') {
            $from_id = $data['from_id'];
            $send_id = $data['send_id'];
            $where = "((send_id={$data['send_id']} and from_id = {$data['from_id']}) or (send_id={$data['from_id']} and from_id = {$data['send_id']})) and is_read=0";
            MessageModel::create()->where($where)->update(['is_read' => 1]);

            $send_list = $redisLink->get('clist_' . $send_id) ?? '[]';

            if ($send_list == '[]') {
                $this->setEmptyRedis($send_id);
                $send_list = $redisLink->get('clist_' . $send_id) ?? '[]';
            }

            $send_list = json_decode($send_list, true);
            if ($send_list && isset($send_list['id_' . $from_id])) {
                $send_list['id_' . $from_id]['is_read'] = 1;
                $redisLink->set('clist_' . $send_id, json_encode($send_list));
            }
        }
        if ($msg_type == 'group') {
            $group_id = $data['send_id'];
            $userId = $data['user_id'];
            GroupMessageReadModel::create()->where(['group_id' => $group_id, 'user_id' => $userId])->update(['is_read' => 1]);


            //获取接收者的会话列表
            $send_list = $redisLink->get('agroupclist_' . $userId) ?? '[]';

            $send_list = json_decode($send_list, true);

            if ($send_list && isset($send_list['id_' . $group_id])) {
                $send_list['id_' . $group_id]['is_read'] = 1;
                // print_r($send_list);
                $redisLink->set('agroupclist_' . $userId, json_encode($send_list)); //clist_1_93
            }
        }
    }

    /**
     * 录音设置消息发送
     * @description
     * @author Mr wang  2019/11/17 0:15
     * @param $server
     * @param $data
     * @throws \EasySwoole\ORM\Exception\Exception
     * @throws \EasySwoole\Redis\Exception\RedisException
     * @throws \Throwable
     */
    public function sendRecordClient($server, $data) {
        $send_id = $data['id'];
        $member = AppMemberModel::create()->where(["id" => $send_id])->findOne();
        $member['type'] = 'record';
        $record_day = [];
        foreach (explode(',', $member['record_day']) as $k => $v) {
            $record_day[] = $v;
        }
        $record_time = [];
        foreach (explode(',', $member['record_time']) as $k => $v) {
            if ($v)
                $record_time[] = $k;
        }

        $member['record_flag'] = $member['record_status'];
        $member['record_day'] = $record_day;
        $member['record_time'] = $record_time;

        $user = UserModel::create()->where(['user_id' => $send_id])->findOne();
        //查询接收者是否在线
        $redisLink = (new RedisResources())->link();
        $send_fd = $redisLink->get('user_' . $user['id']);
        print_r('录音用户fd:' . $send_fd . PHP_EOL);
        print_r('录音用户Uid:' . json_encode($user) . PHP_EOL);
        if ($send_fd) {
            print_r('我要开录音' . $send_id . PHP_EOL);
            print_r('录音发送数据' . json_encode($member) . PHP_EOL);
            $server->push($send_fd, json_encode($member));
        }
    }

    /**
     * 发送通知
     * @param $data
     * @return void
     */
    public function sendNotice($data) {
        //处理通知
        $info = [];
        $from = UserModel::create()->where("id = " . $data['from_id'])->findOne();
        $send = UserModel::create()->where("id = " . $data['send_id'])->findOne();
        $appMember = AppMemberModel::create()->where("id = " . $from['user_id'])->findOne();
        $appPlatform = AppPlatformModel::create()->where('id = ' . $send['platform_id'])->findOne();
        $store_name = '';
        $template_id = $appPlatform['msg_template_id']; //微信模板id

        if ($from['platform_id'] == 3) {

            $appMemberUserId = $appMember['id'];
            if ($appMember['pid'] != 0) {
                $parentAppMember = AppMemberModel::create()->where("id = " . $appMember['pid'])->findOne();
                $appMemberUserId = $parentAppMember['id'];
            }

            $appSeller = AppSellerModel::create()->where("pid = {$send['platform_id']} and mid = " . $appMemberUserId)->findOne();
            $store_name = $appSeller['store_name'];
            $nick_name = $appMember['title'];
        } else {
            $nick_name = $from['name'];
        }

        // $sendAppMember['cid'] = '';


        // if($send['platform_id'] == 3){
        //     $sendAppMember = AppMemberModel::create()->where("id = ".$send['user_id'])->findOne();
        // }

        $info['send']  = ['open_id' => $send['open_id'], 'cid' => $send['cid']];
        $info['from']  = ['nick_name' => $nick_name, 'store_name' => $store_name];
        if ($data['msg_type'] == 2) {
            $data['content'] = '[图片]';
        } elseif ($data['msg_type'] == 4) {
            $data['content'] = '[语音]';
        } elseif ($data['msg_type'] == 5) {
            $data['content'] = '[视频]';
        } else {
            $data['content'] = $data['content'];
        }

        //$data['content'] = $data['msg_type'] == 2 ? '[图片]':($data['msg_type'] == 4 ? '[语音]' : $data['content']);

        if ($template_id && $info['send']['open_id']) {
            $wx_param['type'] = 'msg';
            $wx_param['store_name'] = $info['from']['store_name'];
            $wx_param['nick_name'] = $info['from']['nick_name'];
            $wx_param['open_id'] = $info['send']['open_id'];
            $wx_param['content'] = $data['content'];
            $wx_param['template_id'] = $template_id;
            $wx_param['payload'] = $data['payload'];
            $wx_param['pid'] = $send['platform_id'];
            $url = 'https://shop.zczmer.com/WXAPI/App/sendTemplateMsg';
            $res = $this->httpRequest($url, 'POST', json_encode($wx_param));
            print_r('推送通知返回数据' . json_encode($res) . PHP_EOL);
        }

        if ($info['send']['cid']) {
            $app_param['cids'] = $info['send']['cid'];
            $app_param['title'] = $info['from']['store_name'] . $info['from']['nick_name'];
            $app_param['content'] = $data['content'];
            $app_param['payload'] = $data['payload'];
            $url = 'https://shop.zczmer.com/WXAPI/App/sendPush';
            $res = $this->httpRequest($url, 'POST', json_encode($app_param));
            print_r('推送通知返回数据' . json_encode($res) . PHP_EOL);
        }
    }


    /**
     * CURL请求
     * @param $url 请求url地址
     * @param $method 请求方法 get post
     * @param null $postfields post数据数组
     * @param array $headers 请求header信息
     * @param bool|false $debug  调试开启 默认false
     * @return mixed
     */
    public function httpRequest($url, $method, $postfields = null, $headers = array(), $debug = false) {

        $method = strtoupper($method);
        $ci = curl_init();
        /* Curl settings */
        curl_setopt($ci, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
        curl_setopt($ci, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.2; WOW64; rv:34.0) Gecko/20100101 Firefox/34.0");
        curl_setopt($ci, CURLOPT_CONNECTTIMEOUT, 60); /* 在发起连接前等待的时间，如果设置为0，则无限等待 */
        curl_setopt($ci, CURLOPT_TIMEOUT, 7); /* 设置cURL允许执行的最长秒数 */
        curl_setopt($ci, CURLOPT_RETURNTRANSFER, true);
        // if(!empty($postfields['upload'])){
        //     $file = $postfields['upload']['image'];
        //     $filename = $file['name'];
        //     $filepath = $file['tmp_name'];
        //     $filetype = $file['type'];
        //     $postfields = ['upload' => new \CURLFile(realpath($filepath), $filetype, $filename)];
        // }
        // var_dump($postfields);
        switch ($method) {
            case "POST":
                curl_setopt($ci, CURLOPT_POST, true);
                if (!empty($postfields)) {
                    $tmpdatastr = is_array($postfields) ? http_build_query($postfields) : $postfields;
                    curl_setopt($ci, CURLOPT_POSTFIELDS, $tmpdatastr);
                }
                break;
            default:
                curl_setopt($ci, CURLOPT_CUSTOMREQUEST, $method); /* //设置请求方式 */
                break;
        }
        $ssl = preg_match('/^https:\/\//i', $url) ? TRUE : FALSE;
        curl_setopt($ci, CURLOPT_URL, $url);
        if ($ssl) {
            curl_setopt($ci, CURLOPT_SSL_VERIFYPEER, FALSE); // https请求 不验证证书和hosts
            curl_setopt($ci, CURLOPT_SSL_VERIFYHOST, FALSE); // 不从证书中检查SSL加密算法是否存在
        }
        //curl_setopt($ci, CURLOPT_HEADER, true); /*启用时会将头文件的信息作为数据流输出*/
        curl_setopt($ci, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ci, CURLOPT_MAXREDIRS, 2);/*指定最多的HTTP重定向的数量，这个选项是和CURLOPT_FOLLOWLOCATION一起使用的*/
        curl_setopt($ci, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ci, CURLINFO_HEADER_OUT, true);
        /*curl_setopt($ci, CURLOPT_COOKIE, $Cookiestr); * *COOKIE带过去** */
        $response = curl_exec($ci);
        $requestinfo = curl_getinfo($ci);
        $http_code = curl_getinfo($ci, CURLINFO_HTTP_CODE);
        if ($debug) {
            echo "=====post data======\r\n";
            var_dump($postfields);
            echo "=====info===== \r\n";
            print_r($requestinfo);
            echo "=====response=====\r\n";
            print_r($response);
        }
        curl_close($ci);
        return $response;
        //return array($http_code, $response,$requestinfo);
    }
    public function fanyi($query, $from, $to) {
        $appid = '20240719002103528';
        $seckey = 'KUDr5bpLhXhemce9xx6G';
        $url = 'http://api.fanyi.baidu.com/api/trans/vip/translate';
        // $query='Xin chào, tôi là người hâm mộ của bạn, bạn có thể thêm WeChat';
        $args = array(
            'q' => $query,
            'appid' => $appid,
            'salt' => rand(10000, 99999),
            'from' => $from,
            'to' => $to,

        );
        $args['sign'] = md5($appid . $query . $args['salt'] . $seckey);
        $ret = $this->httpRequest($url, 'post', $args, ['Content-Type' => 'application/x-www-form-urlencoded']);
        //    $ret = json_decode($ret, true);
        print_r($ret);
        return $ret;
    }
}
